<template>
  <div class="update-avatar">
    <img :src="img" id="image" />
    <div class="toolbar">
      <span @click="$emit('close')">取消</span>
      <span @click="confirm">完成</span>
    </div>
  </div>
</template>
<script>
import { Toast } from 'vant'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { getimageupload } from '@/api/getverify'

export default {
  data () {
    return {

    }
  },
  props: {
    img: {
      type: String,
      required: true
    }
  },

  created () {

  },
  mounted () {
    const image = document.getElementById('image')
    this.cropper = new Cropper(image, {
      autoCropArea: 1, // 自动调整裁剪图片
      viewMode: 1, // 只能在裁剪的图片范围内移动
      cropBoxMovable: false, // 禁止裁剪区移动
      aspectRatio: 1,
      dragMode: 'move',
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false
    })
  },

  methods: {
    confirm () {
      Toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: '加载中'
      })
      try {
        console.log(this.cropper)
        this.cropper.getCroppedCanvas().toBlob(async blob => {
          console.log(blob)
          const formdata = new FormData()
          formdata.append('photo', blob)
          console.log(formdata.get('photo'))
          const res = await getimageupload(formdata)
          console.log(res)
          Toast.success('更新成功')
          this.$emit('load-photo', res.photo)
        })
        this.$emit('close')
      } catch (error) {
        Toast.fail('更新失败')
      }
    }
  }
}
</script>
<style scoped lang="less">
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
